<?php


namespace App\Services;


use App\Models\NewRoles;
use Illuminate\Http\Request;
use \Exception;
use Illuminate\Support\Facades\DB;

class RoleService
{
    private const STATUS_ENABLE = 1;

    public function createRole(Request $request)
    {
        $role_id = $request->input('role_id') ?? 0;
        $simpleChineseName = $request->input('simple_chinese_name');
        $result = NewRoles::where("simple_chinese_name", $simpleChineseName)->first();
        if ((!empty($result) && empty($role_id)) || (!empty($result) && !empty($role_id) && $result->id != $role_id)) {
            throw new Exception('简体角色名称已存在', 10001);
        }

        $englishName = $request->input('english_name');
        $result = NewRoles::where("english_name", $englishName)->first();
        if ((!empty($result) && empty($role_id)) || (!empty($result) && !empty($role_id) && $result->id != $role_id)) {
            throw new Exception('英文名称已存在', 10001);
        }
        $traditionChineseName = $request->get('traditional_chinese_name');
        $result = NewRoles::where('traditional_chinese_name', $traditionChineseName)->first();
        if ((!empty($result) && empty($role_id)) || (!empty($result) && !empty($role_id) && $result->id != $role_id)) {
            throw new Exception('繁体名称已存在', 10001);
        }

        $data = [
            'simple_chinese_name' => $simpleChineseName,
            'english_name'        => $englishName,
            'traditional_chinese_name'   => $traditionChineseName,
            'status'                   => self::STATUS_ENABLE,
        ];

        if (!$role_id) {
            $role_id = NewRoles::insertGetId($data);
            if (!$role_id) {
                throw new Exception('保存失败');
            }
            return $role_id;
        }

        $actResult = NewRoles::where('id', $role_id)->update($data);
        if (!$actResult) {
            throw new Exception('保存角色失败');
        }

        return $role_id;
    }

    public function getModulesByRoleId(int $roleId)
    {
        $roleModules = DB::table('xpel_roles')
            ->leftJoin('xpel_role_module', 'xpel_role_module.role_id', 'xpel_roles.id')
            ->where("xpel_roles.id", $roleId)
            ->where('xpel_roles.status', self::STATUS_ENABLE)
            ->select('xpel_role_module.*', 'xpel_roles.simple_chinese_name as role_simple_chinese_name', 'xpel_roles.traditional_chinese_name as role_traditional_chinese_name', 'xpel_roles.english_name as role_english_name')
            ->get();

        return $roleModules ?? [];
    }

    public function getRoles()
    {
        return DB::table('xpel_roles')
            ->where('status', self::STATUS_ENABLE)
            ->select('*')
            ->get();
    }
}